<template>
  <el-form ref="prefixRef" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="打印模板前缀" prop="printStr">
      <el-input v-model="form.printStr" placeholder="请设置打印模板前缀" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">保存</el-button>
      <el-button type="danger" @click="close">关闭</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from 'vue';
import { updateUserProfile } from '@/api/system/user';
import useUserStore from '../../../../store/modules/user';
const userApp = useUserStore();
const props = defineProps({
  user: {
    type: Object
  }
});

const { proxy } = getCurrentInstance();

const form = reactive({
  printStr: ''
});

const rules = ref({
  printStr: [
    { required: true, message: '前缀不能为空', trigger: 'change' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'change' },
    {
      pattern: new RegExp('^[^<>"\'|\\\\]+$'),
      message: '不能包含非法字符',
      trigger: 'change'
    }
  ]
});

function submit() {
  proxy.$refs.prefixRef.validate((valid) => {
    if (valid) {
      updateUserProfile({
        ...props.user,
        printStr: form.printStr
      }).then(() => {
        userApp.getInfo();
        proxy.$modal.msgSuccess('保存成功');
      });
    }
  });
}

function close() {
  proxy.$tab.closePage();
}

// 回显当前登录用户信息
watch(
  () => props.user,
  (user) => {
    if (user) {
      form.printStr = user.printStr;
    }
  },
  { immediate: true }
);
</script>
